package edu.gatech.ealf.magiclenseplaf;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.ScrollPaneUI;
import javax.swing.plaf.basic.BasicComboPopup;

import edu.gatech.ealf.EasyAccessibilityLookAndFeel;

public class MLScrollPaneUI extends ScrollPaneUI implements MouseListener {

    
    
    private ZoomHelper zoomer = null;
    
    public MLScrollPaneUI() {
        super();
    }

    public static ComponentUI createUI(JComponent c) {
        return new MLScrollPaneUI();
    }

    @Override
    public void installUI(JComponent c) {
        super.installUI(c);
        MagicLenseLookAndFeel.getInstance().registerComponentInstallation(this, c);
        zoomer = new ZoomHelper(c);
        c.addMouseListener(this);
        JScrollPane sp = (JScrollPane) c;
        Component[] viewPortComps = sp.getViewport().getComponents();
        for(Component comp : viewPortComps){
            comp.addMouseListener(this);
        }
    }

    public void paint(Graphics g, JComponent c) {
    }

    @Override
    public void uninstallUI(JComponent c) {
        super.uninstallUI(c);
        MagicLenseLookAndFeel.getInstance().registerComponentUninstallation(this, c);
        c.removeMouseListener(this);
        JScrollPane sp = (JScrollPane) c;
        Component[] viewPortComps = sp.getViewport().getComponents();
        for(Component comp : viewPortComps){
            comp.removeMouseListener(this);
        }
        if(zoomer != null){
            zoomer.destroy();
        }
        zoomer = null;
    }

    @Override
    public void update(Graphics g, JComponent c) {
        paint(g, c);
    }

    public void mouseClicked(MouseEvent e) {
        if(e.getButton()== MouseEvent.BUTTON2){
            zoomer.toggleZoomable();
        }
    }


    public void mouseEntered(MouseEvent e) {
        //System.out.println("MLScrollPaneUI.mouseEntered");
        if(!(e.getSource().getClass().getName().equals("javax.swing.plaf.basic.BasicComboPopup$1"))){
            zoomer.zoom();
        }
        
    }

    public void mouseExited(MouseEvent e) {
        boolean hasFocus = zoomer.curComponent.hasFocus();
        zoomer.unZoom();
        if(hasFocus){
            zoomer.curComponent.requestFocusInWindow();
        }
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }
}

